#include "goods.h"
#include "ui_goods.h"

#include <QMessageBox>
#include <QSqlError>



goods::goods(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::goods)
{
    ui->setupUi(this);
    setWindowTitle("仓库货物管理");

    model1= new QSqlRelationalTableModel(this);
    model1->setTable
            ("goods");
    model1->select();
    model1 -> setEditStrategy(QSqlRelationalTableModel::OnManualSubmit);
    model1->setHeaderData(0,Qt::Horizontal,tr("商品号"));
//    model1->setHeaderData(1,Qt::Horizontal,tr("类别号"));
    model1->setHeaderData(1,Qt::Horizontal,tr("商品名"));
    model1->setHeaderData(2,Qt::Horizontal,tr("价格"));
    model1->setHeaderData(3,Qt::Horizontal,tr("数量"));

    ui->tableView->setModel(model1);

    model2 = new QSqlRelationalTableModel(this);
    model2 ->setTable
            ("goods");
    model2 ->select();
    model2 -> setEditStrategy(QSqlRelationalTableModel::OnManualSubmit);
    model2->setHeaderData(0,Qt::Horizontal,tr("商品号"));
    model2->setHeaderData(4,Qt::Horizontal,tr("类别号"));
    model2->setHeaderData(1,Qt::Horizontal,tr("商品名"));
    model2->setHeaderData(2,Qt::Horizontal,tr("价格"));
    model2->setHeaderData(3,Qt::Horizontal,tr("数量"));

    ui->tableView_2->setModel(model2);
    ui->num_out->setMaximum(INT_MAX);
//    ui->num_out->setMaximum(ui->stock->text().toInt());
    ui->num_in->setMaximum(INT_MAX);
}

goods::~goods()
{
    delete ui;
}

void goods::on_SearchAll_clicked()
{
    model1->setTable("goods");
    model1->select();
    model1->setHeaderData(0,Qt::Horizontal,tr("商品号"));
    model1->setHeaderData(1,Qt::Horizontal,tr("商品名"));
    model1->setHeaderData(2,Qt::Horizontal,tr("价格"));
    model1->setHeaderData(3,Qt::Horizontal,tr("数量"));

}

void goods::on_SearchAll_2_clicked()
{
    model2->setTable("goods");
    model2->select();
    model2->setHeaderData(0,Qt::Horizontal,tr("商品号"));
    model2->setHeaderData(1,Qt::Horizontal,tr("商品名"));
    model2->setHeaderData(2,Qt::Horizontal,tr("价格"));
    model2->setHeaderData(3,Qt::Horizontal,tr("数量"));

}

void goods::on_add_clicked()
{
    int addrow = model1->rowCount();
    int id = addrow+1;
    model1->insertRow(addrow);
    model1->setData(model1->index(addrow,0),id);
    model1->submitAll();
}

void goods::on_delete_2_clicked()
{
    int currow = ui->tableView->currentIndex().row();//确定行数
    if(currow==-1)
    {
        QMessageBox::warning(this,tr("删除提醒"),
                                            tr("请选中商品所在行再点击删除"),
                                               QMessageBox::Yes);
    }
    else
    {
        model1->removeRow(currow);

        int issure = QMessageBox::warning(this,tr("删除提醒"),
                                    tr("确认要删除当前行吗？"),
                                       QMessageBox::Yes,QMessageBox::No);
         if(issure==QMessageBox::No)
         {
         model1->revertAll();
         }
         else
         {
            model1->submitAll();
         }
    }
}



void goods::on_ok_clicked()
{
    model1->database().transaction();
       if(model1->submitAll()){
           if(model1->database().commit()){
               QMessageBox::information(this,"提交提醒","修改成功");
           }
       }
       else{
           model1->database().rollback();
           QMessageBox::information(this,"提交提醒",tr("提交错误")
            .arg(model1->lastError().text()),QMessageBox::Yes);
       }
}

void goods::on_search_clicked()
{
    int i = ui->comboBox->currentIndex();
    QString str = ui->lineEdit->text();
    switch (i) {
    case 0:
        model1->setFilter(QString("id = '%1'").arg(str));
        model1->select();
        break;
    case 1:
        model1->setFilter(QString("name = '%1'").arg(str));
        model1->select();
        break;
    }
}

void goods::on_search_2_clicked()
{
    int i = ui->comboBox_2->currentIndex();
    QString str = ui->lineEdit->text();
    switch (i) {
    case 0:
        model2->setFilter(QString("id = '%1'").arg(str));
        model2->select();
        break;
    case 1:
        model2->setFilter(QString("name = '%1'").arg(str));
        model2->select();
        break;
    }
}

void goods::on_revoke_clicked()
{
    model1->revertAll();
}

void goods::on_refresh_clicked()
{
    model2->setTable("goods");
    model2->select();
    model2->setHeaderData(0,Qt::Horizontal,tr("商品号"));
    model2->setHeaderData(1,Qt::Horizontal,tr("商品名"));
    model2->setHeaderData(2,Qt::Horizontal,tr("价格"));
    model2->setHeaderData(3,Qt::Horizontal,tr("数量"));
}

void goods::on_uploadPicture_clicked()
{
    QString picturename = QFileDialog::getOpenFileName(this, "选择商品图片", ".", "Image File(*.png *.jpg *.jpeg *.bmp)");
    if (picturename.isEmpty()) return;
    myPicImg.load(picturename);
    ui->prePictureLabel->setPixmap(QPixmap::fromImage(myPicImg));
}

void goods::on_instock_clicked()
{
    QSqlQuery query;
    query.exec(QString("select categoryid from category where name='%1'").arg(ui->Category_in->currentText()));
    query.next();
    int categoryid = query.value(0).toInt();//将要入库的商品类别
    QString Name = ui->name_in->text();//商品名称
    double inputprice = ui->inprice->text().toDouble();//进价
//    double outputprice = ui->newOutputPriceLineEdit->text().toFloat();//售价
    int count = ui->num_in->value();//入库量
    query.exec(QString("insert into goods(categoryid, name, picture, price, num) values(%1, '%2', NULL, %3, %4)").arg(categoryid).arg(Name).arg(inputprice).arg(count));//插入新入库的商品记录
       //插入照片
    QByteArray picdata;
    QBuffer buffer(&picdata);
    buffer.open(QIODevice::WriteOnly);
    myPicImg.save(&buffer, "JPG");
    QVariant var(picdata);
    QString sqlstr = "update goods set picture=? where name='" + Name + "'";
    query.prepare(sqlstr);
    query.addBindValue(var);
    if(!query.exec())
    {
        QMessageBox::information(0, QObject::tr("提示"), "入库失败，请检测连接");
    }
    else
    {
        QMessageBox::information(0, QObject::tr("提示"), "入库成功");
    }
       //刷新网格信息

    model1= new QSqlRelationalTableModel(this);
    model1->setTable
            ("goods");
    model1->select();
    model1 -> setEditStrategy(QSqlRelationalTableModel::OnManualSubmit);
    model1->setHeaderData(0,Qt::Horizontal,tr("商品号"));
//    model1->setHeaderData(1,Qt::Horizontal,tr("类别号"));
    model1->setHeaderData(1,Qt::Horizontal,tr("商品名"));
    model1->setHeaderData(2,Qt::Horizontal,tr("价格"));
    model1->setHeaderData(3,Qt::Horizontal,tr("数量"));

    ui->tableView->setModel(model1);
}

void goods::showPhoto()
{
    QPixmap photo;
    QModelIndex index;
    QSqlQueryModel *pictureModel = new QSqlQueryModel(this);//商品样照模型数据
    QString name = ui->name_out->text();
    pictureModel->setQuery("select picture from goods where name='" + name + "'");
    index = pictureModel->index(0, 0);
    photo.loadFromData(pictureModel->data(index).toByteArray(), "JPG");
    ui->PictureLabel_2->setPixmap(photo);
}

void goods::onTableSelectChange(int row)
{
    int r = 1;
    if(row != 0) r = ui->tableView_2->currentIndex().row();
    QModelIndex index;
    index = model2->index(r, 0);                   //id
    ui->id_out->setText(model2->data(index).toString());
    index = model2->index(r, 1);                   //名称
    ui->name_out->setText(model2->data(index).toString());
    index = model2->index(r, 2);                   //进价
    ui->in_price->setText(model2->data(index).toString());
    index = model2->index(r, 3);                   //售价
    ui->stock->setText(model2->data(index).toString());
    showPhoto();                                   //商品样照
    ui->num_out->setMaximum(ui->stock->text().toInt());
    QSqlQuery query;
    query.exec(QString("select name from category where categoryid=(select categoryid from goods where Name='%1')").arg(ui->name_out->text()));
    query.next();
    ui->category_out->setText(query.value(0).toString());//类别联动
}

void goods::on_tableView_2_clicked(const QModelIndex &index)
{
    onTableSelectChange(1);
}

void goods::oninformationChange()
{
//    QString name = ui->name_out->currentText();
//    preCommodityModel->setQuery("select OutputPrice, Amount, Picture from commodity where Name='" + name + "'");
    QModelIndex index;
    index = model2->index(0, 2);                   //单价
    ui->lineEdit_5->setText(model2->data(index).toString());
    index = model2->index(0, 3);                   //库存
    ui->stock->setText(model2->data(index).toString());
    ui->num_out->setMaximum(ui->stock->text().toInt());
    //下面开始获取和展示照片
    QPixmap photo;
    index = model2->index(0, 2);
    photo.loadFromData(model2->data(index).toByteArray(), "JPG");
    ui->PictureLabel_2->setPixmap(photo);
    //计算总价
    ui->total_price->setText(QString::number(ui->lineEdit_5->text().toFloat() * ui->num_out->value()));
}

void goods::on_name_out_currentIndexChanged(int index)
{
    oninformationChange();
}

void goods::on_outstock_clicked()
{
    QSqlQuery query;
//    int id = query.value(0).toInt();//本次预售商品编号
    query.exec(QString("select id from goods where name='%1'").arg(ui->name_out->text()));
    query.next();
    int id = query.value(0).toInt();//本次预售商品编号
    int num_out = ui->num_out->value();//预售量
    int num = ui->stock->text().toInt() - num_out;//剩余库存量

//    bool insOk = query.exec(QString("insert into orderitems(OrderID, CommodityID, Count) values(%1, %2, %3)").arg(myOrderID).arg(commodityid).arg(count));//新增订单项
    bool t=query.exec(QString("update goods set num=%1 where id=%2").arg(num).arg(id));//更新库存
    QSqlDatabase::database().transaction();//开始一个事务
    if (t)
    {

        QSqlDatabase::database().commit();
//        if(QSqlDatabase::database().commit())
//        {
        oninformationChange();
        QMessageBox::information(0, QObject::tr("提示"), "出库成功！");
        model2->setTable("goods");
        model2->select();
        ui->tableView_2->setModel(model2);//刷新数据网格
        model2->setHeaderData(0,Qt::Horizontal,tr("商品号"));
        model2->setHeaderData(1,Qt::Horizontal,tr("商品名"));
        model2->setHeaderData(2,Qt::Horizontal,tr("价格"));
        model2->setHeaderData(3,Qt::Horizontal,tr("数量"));
        ui->name_out->setText("");
        ui->category_out->setText("");
        ui->in_price->setText("");
        ui->stock->setText("");
        ui->lineEdit_5->setText("");
        ui->id_out->setText("");
        ui->num_out->setValue(1);
        ui->PictureLabel_2->clear();
//        }
    }
    else
    {
        QSqlDatabase::database().rollback();
    }
}

//    QString otime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
//    QSqlDatabase::database().transaction();//开始一个事务
//    bool ordOk = query.exec(QString("update orders set PaySum=%1, OTime='%2' where OrderID=%3").arg(myPaySum).arg(otime).arg(myOrderID));//下订单
//    bool uptOk = query.exec(QString("update orderitems set Affirm=1, SendGoods=1 where OrderID=%1").arg(myOrderID));//确认发货




